package com.zhugy.comparecode.asm;

import com.zhugy.comparecode.CodeFile;
import com.zhugy.comparecode.CodeLine;
import com.zhugy.comparecode.SingleLineComparableFile;
import com.zhugy.comparecode.util.CommonUtils;

public class AsmFile extends SingleLineComparableFile implements CodeFile {

	public AsmFile(String baseDir, String relativePath) {
		super(baseDir, relativePath);
	}
	
	@Override
	protected CodeLine parseLineWithContent(String content, int index) {
		String c1 = content.replace("\t", " ");;
		int index1;
		index1 = c1.indexOf(';');
		if (index1 >= 0) {
			c1 = c1.substring(0, index1);
			c1 = CommonUtils.trim(c1);
		}
		index1 = labelIndex(c1);
		if (index1 > 0) {
			return new LabelLine(index, CommonUtils.trim(c1.substring(0, index1)), 
					CommonUtils.trim(c1.substring(index1 + 1)));
		}
		index1 = c1.toLowerCase().indexOf(" equ ");
		if (index1 > 0) {
			return new EquLine(index, c1);
		}
		
		index1 = c1.toLowerCase().indexOf(" db ");
		if (index1 >= 0) {
			return new DataLine(index, c1);
		}
		
		index1 = c1.toLowerCase().indexOf(" dw ");
		if (index1 >= 0) {
			return new DataLine(index, c1);
		}
		
		index1 = c1.toLowerCase().indexOf(" dd ");
		if (index1 >= 0) {
			return new DataLine(index, c1);
		}
		
		index1 = c1.indexOf(" ");
		if (index1 > 0) {
			String remain = c1.substring(index1 + 1);
			return new CommandLine(index, c1.substring(0, index1), remain.split(","));
		} else {
			return new CommandLine(index, c1, new String[0]);
		}
	}
	
	private static int labelIndex(String c1) {
		for (int i = 0; i < c1.length(); i++) {
			char c = c1.charAt(i);
			if (c == '"') {
				return -1;
			}
			if (c == ':') {
				return i;
			}
		}
		return -1;
	}

	@Override
	protected boolean isBlankLine(String content) {
		if (CommonUtils.isEmpty(content)) {
			return true;
		}
		if (content.startsWith(";")) {
			return true;
		}
		return false;
	}

}
